import json
import os
import logging
import re
import time
from datetime import datetime
current_dir = os.path.dirname(os.path.abspath(__file__))
logger = setup_logger(__name__, current_dir)

import pandas as pd
import requests

class HttpGenerator:
    def __init__(self):
        self.http_config = self.load_http_config()
        self.prompt_data = self.generate_prompt()
        self.message = []

        output_path = os.path.join(current_dir, 'output')
        os.makedirs(output_path, exist_ok=True)
        self.result_file = output_path + '/result.txt'.format(datetime.now().strftime("%Y_%m_%d"))

    def load_http_config(self):
        config_path = "http_config.json"
        with open(config_path, 'r', encoding='utf-8') as file:
            http_config = json.load(file)
        return http_config

    def generate_prompt(self):
        initial_prompt_path = "initial_prompt.txt"
        cot_path = "cot.txt"
        role = "你是一个分析思维链的分析师，以下是一个模型关于金融风控场景的思维链，这个思维链结合了企业定性及定量的特征数据对企业风险进行多维度的评估。你要对下列思维链从以下几个角度进行评估："
        cot = "\n 以下是原回答的提示词：\n"
        think = "\n 以下是原回答的思维链：\n"
        with open(cot_path, 'r', encoding='utf-8') as file:
            cot += file.read()
        with open(initial_prompt_path, 'r', encoding='utf-8') as file:
            think += file.read()
        final_prompt = role + cot + think
        return final_prompt

    def send_request(self):
        max_retries = 3
        self.http_config['payload']['message'] = self.message
        attempt = 0
        while attempt < max_retries:
            rsp = requests.post(self.http_config['url'], json = self.http_config['payload'], headers=self.http_config['headers'])
            rsp.raise_for_status()
            rsp_data = rsp.json
            content = rsp_data["choices"][0]["message"]["content"]
            reason_content = rsp_data["choices"][0]["message"].get("reasoning_content", "")
            if not content:
                attempt += 1
                print(f"response content is None, retry time: {attempt}.")
            return content, reason_content



